<template>
  <div ref="chartDom" class="chart"></div>
</template>
<script setup>
import { ref, watch, defineProps, nextTick, onUnmounted } from "vue";
import * as echarts from "echarts";
let myChart = null;
const chartDom = ref(null);
const props = defineProps({
  option: {
    type: Object,
    default: () => {},
  },
  autoPlay: {
    type: Boolean,
    default: true,
  },
});
nextTick(() => {
  myChart = echarts.init(chartDom.value);
  setChart();
  window.addEventListener("resize", () => {
    myChart.resize();
  });
});
watch(props.option, () => {
  if (setinv != null) {
    clearInterval(setinv);
    setinv = null;
  }
  setChart();
});

onUnmounted(() => {
  myChart.clear();
  if (setinv != null) {
    clearInterval(setinv);
    setinv = null;
  }
});
let setinv = null;
function setChart() {
  if (Object.keys(props.option).length > 0) {
    myChart.setOption(props.option);
    
    if (props.autoPlay) {
      let nowIndex = 0;
      setinv = setInterval(() => {
        // 清除之前的高亮状态
        myChart.dispatchAction({ type: "downplay" });

        // 高亮当前索引对应的数据点
        myChart.dispatchAction({
          type: "highlight",
          seriesIndex: 0,
          dataIndex: nowIndex,
        });
        myChart.dispatchAction({
          type: "highlight",
          seriesIndex: 1,
          dataIndex: nowIndex,
        });

        myChart.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: nowIndex,
        });
        nowIndex++;
        if (props.option.series[0].data.length === nowIndex) {
          nowIndex = 0;
        }
      }, 1000);
    }
  }
}
</script>
<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
